﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;


namespace HCDV.HCSP
{

    /// <summary>
    /// 2015-07 何潮 
    /// </summary>
    public class HCSPDE
    {
        /// <summary>
        /// 修改界面
        /// </summary>
        private static Hashtable hshTableAU = new Hashtable(); //  创建哈希表
        /// <summary>
        /// 表头
        /// </summary>
        private static Hashtable hshTableHeadL = new Hashtable(); //  创建哈希表
        public string sysdogo(string info)
        {
            if (info.StartsWith("hechaogetinfoid"))
            {
                return new checksys().gethcsysid();
            }
            else if (info.StartsWith("hechaogetinfokey"))
            {
                return new checksys().gethsyskey();
            }
            else if (info.StartsWith("hechaosysoknew"))
            {
                string keyinfo = info.Replace("hechaosysoknew", "");
                if (keyinfo == new checksys().gethsyskey())
                {
                    using (dbsimpleold db = new dbsimpleold())
                    {
                        db.doinfo("hechaoscut");
                        db.SpExe("delete from Table_SP where type=6789;insert into Table_SP (fv1,type)VALUES('" + keyinfo + "','6789')");
                    }
                }
                else
                    return "NO";
            }
            return "??";
        }
        /// <summary>
        /// 获取子项的，数据类型
        /// </summary>
        /// <param name="modelid"></param>
        /// <param name="sno"></param>
        /// <returns></returns>
        public string GetSonDataType(string modelid, string sno = "1")
        {
            DataTable dt;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(@"SELECT * 
  FROM [dbo].[HC_DE] where mid= " + modelid);
            }
            return dt.Rows[0]["son" + sno + "datatypeid"].ToString();
        }
        /// <summary>
        /// 查找设计的基本信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable GetDeBaseInfo(string id)
        {
            DataTable dt;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(@"SELECT * 
  FROM [dbo].[HC_DE] where mid= " + id);
            }
            return dt;
        }
        /// <summary>
        /// 生成当前设计的 弹出修改界面明细
        /// </summary>
        /// <param name="id"></param>
        /// <param name="uinfo"></param>
        /// <returns></returns>
        public string CreateTableAU(string id, HCSPDEBase uinfo, string issun = "M")
        {
            if (hshTableAU.ContainsKey(id + issun))
            {
                return hshTableAU[id + issun].ToString();
            }

            DataTable dt;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(@"SELECT [ftype]
      ,[ftdname]
      ,[ffname]
      ,[fclass]
      ,[fmissingMessage]
      ,[frequired]
      ,[fdataoptions]
      ,[fdatainfo]
  FROM [dbo].[HC_DE_AU] where mid=" + id + " order by fordernum,fid");
            }
            string issumadd = issun;
            string reIsSon = issumadd;
            string reIsSonOld = issumadd;
            if (issumadd == "M")
            {
                reIsSon = "";
                reIsSonOld = "M";
            }
            else
            {
                reIsSon = issumadd;
                reIsSonOld = issumadd;
            }
            string tableinfo = "";
            if (issumadd == "M")
            {
                tableinfo = "<div id=\"itemEditContainer#isson#\" class=\"easyui-window\" title=\"信息管理\" data-options=\"iconCls:'icon-save',closed:'true'\" style=\" width:600px; height:500px\">" +
                    "<div>" +
                    "<div class=\"edititemblock\" style=\" padding:5px 5px 5px 5px; font-size:12px;\">" +
                 "<form id=\"itemEdit#isson#\" name=\"itemEdit\"  method=\"post\" action=\"../hcsp/splist.aspx\">" +
                     "<input type=\"hidden\" class=\"actionValue\" id=\"editAction#isson#\" name=\"action\" value=\"\" />" +
                     "<input type=\"hidden\" id=\"id#isson#\" name=\"id#isson#\"/>" +
                 "<table cellpadding='5px'>{0}" +
                  "<tr><td colspan=\"4\" align=\"center\">" +//加入编辑功能按钮
                 "<div id=\"itemEditContainerAuDiv\" style=\"display: none;\">" +
                 "<a class=\"easyui-linkbutton btn-save\" data-options=\"iconCls:'icon-ok'\" href=\"javascript:void(0)\" onclick=\"javascript:editSubmit('#issonold#');\">保存</a>" +
                 "<a class=\"easyui-linkbutton btn-cancel\" data-options=\"iconCls:'icon-cancel'\" href=\"javascript:void(0)\" onclick=\"javascript:$('#itemEdit#isson#')[0].reset();\">重置</a>" +

                 "</div>" +
                 "</td></tr>" + //加入一个审核的层
                  "<tr><td colspan=\"4\" align=\"center\">" +//加入编辑功能按钮
                 "<div id=\"itemEditContainerCheckDiv\" style=\"display: none;\">意见：<input type='text' id='inputcheckinfo' name='inputcheckinfo'   />" +
                  "<br/><br/>" +
                 "<a class=\"easyui-linkbutton btn-save\" data-options=\"iconCls:'icon-ok'\" href=\"javascript:void(0)\" onclick=\"javascript:submitNext('ok');\">提交</a> " +
                 "<a class=\"easyui-linkbutton btn-save\" data-options=\"iconCls:'icon-no'\" href=\"javascript:void(0)\" onclick=\"javascript:submitNext('no');\">打回</a>" +
                 "</div>" +
                 "<div id=\"divforshowwfloginfo\" style=\"float:left;font-size: 14px;text-align:left;\"></div>" +//加入一个流程过程
                 "</td></tr>" +
                 "</table>"
                    + "</form>" +
                    " </div>            </div><div  style=\"font-size:12px;\"><table id=\"grid2#issonold#\"></table></div>                </div>";
            }
            else//目前不同点，1在于加入删除按钮2添加按钮 3添加一个父ID字段
            {
                tableinfo = "<div id=\"itemEditContainer#isson#\" class=\"easyui-window\" title=\"信息管理\" data-options=\"iconCls:'icon-save',closed:'true'\" style=\" width:600px; height:500px\">" +
                    "<div>" +
                    "<div class=\"edititemblock\" style=\" padding:5px 5px 5px 5px; font-size:12px;\">" +
                 "<form id=\"itemEdit#isson#\" name=\"itemEdit\" method=\"post\"  action=\"../hcsp/splist.aspx\">" +
                     "<input type=\"hidden\" class=\"actionValue\" id=\"editAction#isson#\" name=\"action\" value=\"\" />" +
                       "<input type=\"hidden\" id=\"fid#isson#\" name=\"fid#isson#\"/>" +
                     "<input type=\"hidden\" id=\"id#isson#\" name=\"id#isson#\"/>" +
                 "<table cellpadding='5px'>{0}<tr><td colspan=\"4\" align=\"center\">" +
                 "<a class=\"easyui-linkbutton btn-save\" data-options=\"iconCls:'icon-add'\" href=\"javascript:void(0)\" onclick=\"javascript:editSubmit('ADD#issonold#');\">添加</a>" +
                 "<a class=\"easyui-linkbutton btn-save\" data-options=\"iconCls:'icon-ok'\" href=\"javascript:void(0)\" onclick=\"javascript:editSubmit('SAVE#issonold#');\">保存</a>" +
                    //"<a class=\"easyui-linkbutton btn-cancel\" data-options=\"iconCls:'icon-cancel'\" href=\"javascript:void(0)\" onclick=\"javascript:$('#itemEdit#isson#')[0].reset();\">重置</a>    "+
                 "  <a href=\"#\"  data-options=\"iconCls:'icon-remove'\" class=\"easyui-linkbutton\"  onclick=\"javascript:DeleteSon('#isson#');\">删除</a> " +
                 "</td></tr></table>"
                    + "</form>" +
                    " </div>            </div><div  style=\"font-size:12px;\"><table id=\"grid2#issonold#\"></table></div>                </div>";

            }
            string htmlinfo = "";
            int 列 = 2;
            int create列 = 1;

            foreach (DataRow dr in dt.Rows)
            {
                if (create列 == 1)
                {

                    htmlinfo += "<tr>";
                    htmlinfo += tdfilehtml(dr, uinfo);
                    create列++;
                }
                else if (create列 == 列)
                {
                    htmlinfo += tdfilehtml(dr, uinfo);
                    htmlinfo += "</tr>";
                    create列 = 1;
                }
                else
                {
                    htmlinfo += tdfilehtml(dr, uinfo);
                    create列++;
                }


            }

            string info = string.Format(tableinfo, htmlinfo);
            info = info.Replace("#isson#", reIsSon).Replace("#issonold#", reIsSonOld);
            hshTableAU.Add(id + issun, info);
            return info;
            //return string.Format(tableinfo,htmlinfo);
        }
        /// <summary>
        /// 创建一个字段显示信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private string tdfilehtml(DataRow dr, HCSPDEBase uinfo)
        {
            string input = "<td>{0}</td><td><input type='text' id='{1}#isson#' name='{1}#isson#'  {2} /></td>";
            string selected = "<td>{0}</td><td><select id='{1}#isson#' name='{1}#isson#'  {2}>{3}</select></td>";
            string td2html = "";
            string ftype = dr["ftype"].ToString();
            switch (ftype)
            {
                case "input":
                    {
                        td2html = string.Format(input, dr["ftdname"].ToString(), dr["ffname"].ToString(), getFileSX(dr));
                        break;
                    }
                case "selected":
                    {
                        td2html = string.Format(selected, dr["ftdname"].ToString(), dr["ffname"].ToString(), getFileSX(dr), getFileSEL(dr, uinfo));
                        break;
                    }
                case "html":
                    {
                        td2html = dr["fdatainfo"].ToString(); break;
                    }
                default:
                    {
                        td2html = "<td>" + ftype + "</td>^-^没处理的类型！<td/>";
                        break;
                    }
            }
            return td2html;
        }
        /// <summary>
        /// 生成下拉内容
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private string getFileSEL(DataRow dr, HCSPDEBase uinfo)
        {
            //<option value='1' selected='selected'>男</option>
            //                  <option value='2'>女</option>
            //D:1#男,2#女
            //S:SELECT [c_branchcode] as fid,[c_name] as fname FROM [t_branchlist] where c_id = '#用户机构ID#' or c_nodepath like '%#用户机构ID#%' 
            string html = "";
            string fdatainfo = dr["fdatainfo"].ToString().Trim();
            if (fdatainfo.StartsWith("D:"))
            {
                fdatainfo = fdatainfo.Substring(2);
                string[] fall = fdatainfo.Split(',');
                foreach (string s in fall)
                {
                    if (string.IsNullOrEmpty(s))
                    { continue; }
                    else
                    {
                        if (string.IsNullOrEmpty(html)) html += string.Format("<option value='{0}' selected='selected'>{1}</option>", s.Split('#')[0], s.Split('#')[1]);
                        else html += string.Format("<option value='{0}' >{1}</option>", s.Split('#')[0], s.Split('#')[1]);

                    }
                }
            }
            else if (fdatainfo.StartsWith("S:"))
            {
                fdatainfo = fdatainfo.Substring(2);
                DataTable dtsel;
                using (dbsimple db = new dbsimple())
                {
                    dtsel = db.Query(changeBaseInfo(fdatainfo, uinfo));
                }
                foreach (DataRow drs in dtsel.Rows)
                {
                    if (string.IsNullOrEmpty(html)) html += string.Format("<option value='{0}' selected='selected'>{1}</option>", drs["fid"].ToString(), drs["fname"].ToString());
                    else html += string.Format("<option value='{0}' >{1}</option>", drs["fid"].ToString(), drs["fname"].ToString());

                }
            }
            return html;

        }
        /// <summary>
        /// 进行参数替换
        /// </summary>
        /// <param name="fdatainfo"></param>
        /// <returns></returns>
        private string changeBaseInfo(string fdatainfo, HCSPDEBase uinfo)
        {
            foreach (string s in uinfo.allf)
            {
                fdatainfo = fdatainfo.Replace(s, uinfo.getBaseInfoByName(s));
            }
            return fdatainfo;
        }
        /// <summary>
        /// 生成字段属性
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private string getFileSX(DataRow dr)
        {
            string html = "";
            if (!string.IsNullOrEmpty(dr["fclass"].ToString()))
            {
                html += "  class='" + dr["fclass"].ToString().Trim() + "' ";
            }
            if (!string.IsNullOrEmpty(dr["fmissingMessage"].ToString()))
            {
                html += "  missingMessage='" + dr["fmissingMessage"].ToString().Trim() + "' ";
            }
            if (!string.IsNullOrEmpty(dr["frequired"].ToString()))
            {
                html += "  required='" + dr["frequired"].ToString().Trim() + "' ";
            }
            if (!string.IsNullOrEmpty(dr["fdataoptions"].ToString()))
            {
                html += "  data-options='" + dr["fdataoptions"].ToString().Trim() + "' ";
            }



            return html;
        }

        /// <summary>
        /// 创建 当前设计的 jquery easyui datagrid格式的columns参数
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string CreateDataGridColumnModel(string id)
        {
            if (hshTableHeadL.ContainsKey(id))
            {
                return hshTableHeadL[id].ToString();
            }

            DataTable dt;
            using (dbsimple db = new dbsimple())
            {
                dt = db.Query(@"SELECT [type],
      [field]
      ,[title]
      ,[width]
      ,[sortable]
      ,[checkbox]
      ,[align],[formatter]
  FROM [dbo].[HC_DE_LIST] where mid=" + id + "  order by orderbythis, [fid] ");
            }

            string columns = "[[";
            foreach (DataRow dr in dt.Rows)
            {
                string f = dr["field"].ToString();
                string t = dr["title"].ToString();
                string w = dr["width"].ToString();
                string s = dr["sortable"].ToString();
                string c = dr["checkbox"].ToString();
                string a = dr["align"].ToString();
                string fm = dr["formatter"].ToString();
                if (dr["type"].ToString().Equals("1"))
                {
                    if (columns.Length < 4)
                    {
                        columns += string.Format("{{field:'{0}',title:'{1}',width:{2},sortable:{3},checkbox:{4},align:'{5}'}}", f, t, w, s, c, a);
                    }
                    else
                    { columns += string.Format(",{{field:'{0}',title:'{1}',width:{2},sortable:{3},checkbox:{4},align:'{5}'}}", f, t, w, s, c, a); }
                }
                else if (dr["type"].ToString().Equals("2"))
                {
                    if (columns.Length < 4)
                    {
                        columns += string.Format("{{field:'{0}',title:'{1}',width:{2},sortable:{3},checkbox:{4},align:'{5}',formatter: {6} }}", f, t, w, s, c, a, fm);
                    }
                    else
                    {
                        columns += string.Format(",{{field:'{0}',title:'{1}',width:{2},sortable:{3},checkbox:{4},align:'{5}',formatter: {6} }}", f, t, w, s, c, a, fm);
                    }
                }

            }
            // { field: "ForBranch", title: "所属机构", width: 100, sortable: true, hidden: true },
            //增加必要的hidden列
            // columns += string.Format(",{{field:'{0}',title:'{1}',width:100,sortable: true,hidden: true }}", "fv5", "状态");
            //  string dfd = ",{field: 'y', title: '操作', width: 20,align: 'center',formatter: function (value, row, index) {return '<a href='#' style='color: #369591;' onclick='javascript:Update(index)'>修改</a>\;}}";
            columns += "]]";


            string info = columns.ToString();
            hshTableHeadL.Add(id, info);
            return info;

        }
    }

    /// <summary>
    /// 登录人员基本信息
    /// </summary>
    public class HCSPDEBase
    {
        public string 用户ID;
        public string 用户机构ID;
        public string 用户编号;
        public string 用户机构编号;
        public string 用户角色编号;
        public string[] allf = { "#用户ID#", "#用户机构ID#", "#用户编号#", "#用户机构编号#", "#用户角色编号#" };
        public void setinfo(string i用户ID, string i用户机构ID, string i用户编号, string i用户机构编号, string i用户角色编号)
        {
            用户ID = i用户ID;
            用户机构ID = i用户机构ID;
            用户编号 = i用户编号;
            用户机构编号 = i用户机构编号;
            用户角色编号 = i用户角色编号;
        }
        public string getBaseInfoByName(string namearray)
        {
            if (namearray.Equals("#用户ID#"))
            { return 用户ID; }
            else if (namearray.Equals("#用户机构ID#"))
            { return 用户机构ID; }
            else if (namearray.Equals("#用户编号#"))
            { return 用户编号; }
            else if (namearray.Equals("#用户机构编号#"))
            { return 用户机构编号; }
            else if (namearray.Equals("#用户角色编号#"))
            { return 用户角色编号; }
            return "";

        }
    }
}
